<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\Radar\Action\Sidebar;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Contract\RequestInterface;
use MoChat\App\Common\Middleware\SidebarAuthMiddleware;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Plugin\Radar\Contract\RadarContract;
use MoChat\Plugin\Radar\Contract\RadarRecordContract;

/**
 * 互动雷达- 数据详情.
 *
 * Class Show.
 * @Controller
 */
class Show extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @var RequestInterface
     */
    protected $request;

    /**
     * @Inject
     * @var RadarContract
     */
    protected $radarService;

    /**
     * @Inject
     * @var RadarRecordContract
     */
    protected $radarRecordService;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    private $logger;

    /**
     * @RequestMapping(path="/sidebar/radar/show", methods="get")
     * @Middlewares({
     *     @Middleware(SidebarAuthMiddleware::class)
     * })
     * @return array 返回数组
     */
    public function handle(): array
    {
        $user = user();
        // 参数验证
        $this->validated($this->request->all());
        // 接收参数
        $params['id'] = (int) $this->request->input('id');
        $params['name'] = $this->request->input('name', '');
        $params['employeeId'] = $user['id'];

        // 查询数据
        return $this->handleData($params);
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [
            'id' => 'required | integer | min:0 | bail',
        ];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [
            'id.required' => '活动ID 必填',
            'id.integer' => '活动ID 必需为整数',
            'id.min  ' => '活动ID 不可小于1',
        ];
    }

    private function handleData(array $params): array
    {
        // 互动雷达点击信息
        $list = ['todayPeople' => 0, 'todayNum' => 0, 'totalPeople' => 0, 'totalNum' => 0, 'todayContact' => [], 'totalContact' => []];
        $radarRecords = $this->radarRecordService->getRadarRecordByRadarIdEmployeeIdCreatedAtNickname($params['id'], $params['employeeId'], '', $params['name'], ['nickname', 'avatar', 'contact_id', 'created_at']);
        if (empty($radarRecords)) {
            return $list;
        }
        // 总数据
        $list['totalNum'] = count($radarRecords); // 总点击次数
        $contactIds = array_column($radarRecords, 'contactId');
        $contactNums = array_count_values($contactIds);
        $list['totalPeople'] = count(array_unique($contactIds)); // 总点击人数
        $contactRadarRecords = array_column($radarRecords, null, 'contactId');
        foreach (array_unique($contactIds) as $item) {
            $last = $this->radarRecordService->getRadarRecordByRadarIdContactIdEmployeeId($params['id'], $item, $params['employeeId'], ['created_at']);
            $list['totalContact'][] = [
                'contactId' => $contactRadarRecords[$item]['contactId'],
                'contactName' => $contactRadarRecords[$item]['nickname'],
                'contactAvatar' => $contactRadarRecords[$item]['avatar'],
                'clickNum' => $contactNums[$item],
                'lastTime' => $last['createdAt'] ?? '',
            ];
        }
        // 今日数据
        $todayRadarRecords = $this->radarRecordService->getRadarRecordByRadarIdEmployeeIdCreatedAtNickname($params['id'], $params['employeeId'], date('Y-m-d'), $params['name'], ['nickname', 'avatar', 'contact_id', 'created_at']);
        if (empty($todayRadarRecords)) {
            return $list;
        }
        $list['todayNum'] = count($todayRadarRecords); // 今日点击次数
        $todayContactIds = array_column($todayRadarRecords, 'contactId');
        $todayContactNums = array_count_values($todayContactIds);
        $list['todayPeople'] = count(array_unique($todayContactIds)); // 今日点击人数
        $TodayContactRadarRecords = array_column($todayRadarRecords, null, 'contactId');
        foreach (array_unique($todayContactIds) as $item) {
            $last = $this->radarRecordService->getRadarRecordByRadarIdContactIdEmployeeId($params['id'], $item, $params['employeeId'], ['created_at']);
            $list['todayContact'][] = [
                'contactId' => $TodayContactRadarRecords[$item]['contactId'],
                'contactName' => $TodayContactRadarRecords[$item]['nickname'],
                'contactAvatar' => $TodayContactRadarRecords[$item]['avatar'],
                'clickNum' => $todayContactNums[$item],
                'lastTime' => $last['createdAt'] ?? '',
            ];
        }

        return $list;
    }
}
